//
//  XSWelcomeView.swift
//  XS微博
//
//  Created by 王小帅 on 2016/11/27.
//  Copyright © 2016年 王小帅. All rights reserved.
//

import UIKit
import SDWebImage

class XSWelcomeView: UIView {

  
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var tipLabel: UILabel!
    
    @IBOutlet weak var bottomConstrains: NSLayoutConstraint!

    
    
    /// 定义一个类方法供外界调用
    class func welcomeView()->XSWelcomeView{
        
        // 从xib加载view
        let nib = UINib(nibName: "XSWelcomeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! XSWelcomeView
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    
    // 在界面一架载就获取用户信息
    override func awakeFromNib() {
        super.awakeFromNib()
        // 加载头像
        let url = URL(string: XSNetworkTools.shared.userAccess.avatar_large!)
        iconView.sd_setImage(with: url!, placeholderImage: UIImage(named: "avatar_default_big"))
        // 设置圆角
        iconView.layer.cornerRadius = iconView.bounds.width * 0.5
        iconView.layer.masksToBounds = true
    }
    
    
    
    
    /// 视图已经被加载到了window做一个欢迎动画
    override func didMoveToWindow() {
        super.didMoveToWindow()
        // 如果没有先进行一次更新约束 那么整个界面回从右下角缓慢展开
        // 所以先对主界面进行更新约束 然后在让头像做动画
        self.layoutIfNeeded()
        
        // 让头像的底部约束上移 因为label参照头像所以它自动回跟着移动
        bottomConstrains.constant = bounds.size.height - 200;
        
        // 加入动画
        UIView.animate(withDuration: 1.0,
                       delay: 0,
                       usingSpringWithDamping: 0.7,
                       initialSpringVelocity: 0,
                       options: [],
                       animations: {
                        // 更新约束
                        self.layoutIfNeeded()
                        
        }, completion: {(isCompleted) in
        
            // 让欢迎文字慢慢显示
            UIView.animate(withDuration: 1, animations: {
                self.tipLabel.alpha = 1
            }, completion: { (Bool) in

                // 更高状态栏
                IsHidedStatusBar = false
                self.closeSelf()
            })
        })
    }
    
    
    
    /// 关闭当前视图
    private func closeSelf(){
        self.removeFromSuperview()
        // 发送关闭通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: NewFeatureAndWeclcomRemoveFromSuperView), object: nil)
        
    }

}
